import React, {Component} from 'react';
import {
  View,
  Image,
  TouchableOpacity,
  Text,
  ScrollView,
} from 'react-native';

import CommonStyles from '../../common/CommonStyles';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import BaseComponent from '../common/BaseComponent';
import CommonDataListView from '../common/CommonDataListView';
import Config from '../../config';
import Platform from 'Platform';

const BUTTON_HEIGHT = 80;

export default class CommonTabView extends BaseComponent  {
  constructor(props) {
    super(props);
    this.state.isRefreshing = false;
    this.state.scrollEnabled = Platform.OS === 'ios';
    this.state.currentIndex = 0;

    this._scrollView = null;

    this._pageWidth = this.props.style.width;
    this._pageHeight = this.props.style.height - SizeUtils.translateDesignHeightToCode(BUTTON_HEIGHT);
    this._buttonWidth = parseInt(this._pageWidth / this.props.tabDatas.length);

    this._clickTopBtnTimer = null;
  }

  render() {
    return(
      <View style={this.props.style}>
        {this._renderTopButton()}
        {this._renderScrollView()}
      </View>
    )
  }

  _renderScrollView() {
    return(
      <ScrollView style={{width:this._pageWidth,
          height:this._pageHeight}}
        ref={(ref) => this._scrollView = ref}
        horizontal={true}   // 水平方向
        showsHorizontalScrollIndicator={false}  // 水平指示器
        showsVerticalScrollIndicator={false}    // 垂直指示器
        pagingEnabled={true}    // 开启分页功能
        alwaysBounceHorizontal={false} //弹性拉动一截
        onScroll={this._onScroll.bind(this)}
        scrollEnabled={this.state.scrollEnabled}
      >
        {this.props.tabDatas.map(
          (tabData, index) => {
            return this._getPage(tabData, index);
          }
        )}
      </ScrollView>
    )
  }

  _onScroll(event) {
    let x = event.nativeEvent.contentOffset.x;
    let index = Math.round(x / this._pageWidth);
    console.log("round", index, x / this._pageWidth, x, this._pageWidth);
    if(this.state.currentIndex != index) {
      this.setState({
        currentIndex:index,
      })
    }
  }

  _changeTab(index) {
    this.setState({
      currentIndex:index,
    });
  }

  _getPage(tabData, index) {
    let type = index + 1;
    if(type == 3) {
      type = 4;
    }
    else if(type == 4) {
      type = 3;
    }
    return(
      <PageView key={index} isCurrent={this.state.currentIndex == index}
          type={type} style={{width:this._pageWidth, height:this._pageHeight}}
          noEmpty = {true} tabData = {tabData}
          pageData = {this.props.pageData} autoInitRequest={index == 0}
          requestData = {this._onPageViewRequestData.bind(this)}
          onRenderHeader = {this._onPageViewRenderHeader.bind(this)}
          onRenderItem = {this._onPageViewRenderItem.bind(this)}
          onPressItem = {this._onPageViewPressItem.bind(this)}
          />
    )
  }

  _onPageViewPressItem(data, tabData) {
    this.props.onPageViewPressItem && this.props.onPageViewPressItem(data, tabData);
  }

  _onPageViewRenderItem(data, index, tabData) {
     if(this.props.onPageViewRenderItem) {
       return this.props.onPageViewRenderItem(data, index, tabData);
     }
  }

  _onPageViewRenderHeader(tabData) {
    if(this.props.onPageViewRenderHeader) {
      return this.props.onPageViewRenderHeader(tabData);
    }
  }

  _onPageViewRequestData(page, listView, tabData) {
    this.props.onPageViewRequestData && this.props.onPageViewRequestData(page, listView, tabData);
  }

  setHorizontalDisable(){
      this.setState({
        scrollEnabled:false
      })
  }

   setHorizontalEnable(){
      this.setState({
        scrollEnabled:true
      })
  }

  _renderTopButton() {
    return(
      <View style={{width:this._pageWidth, height:SizeUtils.translateDesignHeightToCode(BUTTON_HEIGHT),
          flexDirection:"row", justifyContent:"center", alignItems:"center", borderBottomWidth:SizeUtils.translateDesignNumToCode(3),
          borderColor:"#eeeeee", backgroundColor:"#ffffff"}}>
        {this.props.tabDatas.map(
          (tabData, index) => {
            return this._getButton(tabData, index);
          }
        )}
      </View>
    )
  }

  _getButton(tabData, index) {
    let type = index;
    if(type == 2) {
      type = 3;
    }
    else if(type == 3) {
      type = 2;
    }
    return(
      <TouchableOpacity key={index} onPress={()=>this._onPressBtn(index)} style={{width:this._buttonWidth,
          height:SizeUtils.translateDesignHeightToCode(BUTTON_HEIGHT), flexDirection:"column", justifyContent:"center", alignItems:"center",
          }}>
        <View style={{height:SizeUtils.translateDesignHeightToCode(76), justifyContent:"center", alignItems:"center",}}>
          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(28), color:index == this.state.currentIndex ? "#db3132": "#666666"}}>
            {tabData.buttonLabel}
          </Text>
        </View>
        <View style={{borderColor:"#db3132", borderBottomWidth:index == this.state.currentIndex ? SizeUtils.translateDesignNumToCode(5) : 0,
          width:SizeUtils.translateDesignWidthToCode(60), height:SizeUtils.translateDesignHeightToCode(5)}}>
        </View>
      </TouchableOpacity>
    )
  }

  _onPressBtn(index) {
    if(this._clickTopBtnTimer) {
      return;
    }
    this._clickTopBtnTimer = setTimeout(() => {
      this.setState({
        scrollEnabled:Platform.OS === 'ios',
      });
      this._clearClickTopBtnTimer();
    }, 500);
    this.setState({
      scrollEnabled:true,
    }, ()=>this._scrollView.scrollTo({x:index * this._pageWidth}));
  }

  _clearClickTopBtnTimer() {
    this._clickTopBtnTimer && clearTimeout(this._clickTopBtnTimer)
    this._clickTopBtnTimer = null;
  }
};

class PageView extends CommonDataListView {
  constructor(props) {
    super(props);

    this._initComplete = this.props.autoInitRequest === true;
  }

  _dealComponentWillUpdate(nextProps, nextState) {
    super._dealComponentWillUpdate(nextProps, nextState);

    if(this._initComplete === false && nextProps.isCurrent === true) {
      this._initComplete = true;
      this.doRefresh();
    }
  }

  _onPressItem(data) {
    this.props.onPressItem && this.props.onPressItem(data, this.props.tabData);
  }

  _onRenderItem(data, index) {
     if(this.props.onRenderItem) {
       return this.props.onRenderItem(data, index, this.props.tabData);
     }
  }

  _onRenderHeader() {
    if(this.props.onRenderHeader) {
      return this.props.onRenderHeader(this.props.tabData);
    }
  }

  _requestData(page) {
    this.props.requestData && this.props.requestData(page, this, this.props.tabData);
  }
}
